package org.kaer.election.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kaer.election.R;
import org.kaer.election.adapter.SearchCandidateAdapter;
import org.kaer.election.bean.Candidate;
import org.kaer.election.bean.Positions;
import org.kaer.election.bean.SelectedElection;
import org.kaer.election.ite.OnRecycleItemClickListener;
import org.kaer.election.ui.ElectionActivity;
import org.kaer.election.utils.CommonUtil;
import org.kaer.election.utils.GridItemDecoration;
import org.kaer.election.utils.JSONKeys;
import org.kaer.election.utils.LogUtils;
import org.kaer.election.widget.LoadMoreFooterView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lizj on 2016/7/25.
 */
public class SearchCandidateFragment extends BaseFragment implements View.OnClickListener, OnLoadMoreListener {
    private TextView allowNumTv, allowNumPromptTv, selNumTv, selNumPromptTv, leastNumTv, leastNumPromptTv;
    private EditText searchEt;
    private Button queryBtn;
    private LinearLayout descLL;
    private IRecyclerView candidateGv;
    private SearchCandidateAdapter canAdapter;
    private ArrayList<Candidate> selList;
    private List<Candidate> recordList;
    private SelectedElection election;
    private HashMap<Integer, Integer> recordMap;
    private Gson mGson;
    private Positions posInfo;
    private int totalCount, currentCount;  //该索引能返回的总数,该索引已返回的数量
    private final int QUERY_COUNT = 8; // 每次请求的数量
    private boolean hasMore;
    private LoadMoreFooterView loadMoreFooterView;


    public static SearchCandidateFragment newInstance(Bundle mBundle) {
        SearchCandidateFragment fragment = new SearchCandidateFragment();
        fragment.setArguments(mBundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_searchcandidate;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initPosDescView();
        candidateGv = (IRecyclerView) findView(R.id.searchCandidateGv);
        candidateGv.setLayoutManager(new GridLayoutManager(mContext, 2));
        candidateGv.addItemDecoration(new GridItemDecoration(2, 2));
        candidateGv.addOnItemTouchListener(new OnRecycleItemClickListener(candidateGv) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                LogUtils.i("onItemClick vh AdapterPosition =" + vh.getAdapterPosition());
                updateCanditaInfo(vh.getAdapterPosition() - 2);
            }
        });
        loadMoreFooterView = /*new LoadMoreFooterView(mContext)*/(LoadMoreFooterView) candidateGv.getLoadMoreFooterView();
        candidateGv.setOnLoadMoreListener(this);
        //we can set view
        searchEt = (EditText) findView(R.id.searchCandidate_etFilter);
        //searchEt.addTextChangedListener(new SearchWatcher());
        searchEt.setImeActionLabel(mContext.getResources().getString(R.string.query), EditorInfo.IME_ACTION_DONE);
        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                LogUtils.i("actionId = " + actionId);
                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    onSearch(v.getText().toString());
                }
                return false;
            }
        });
        findView(R.id.election_btnDone).setOnClickListener(this);
        queryBtn = (Button) findView(R.id.election_btnQuery);
        queryBtn.setOnClickListener(this);
        initData();
    }

    private void initData() {
        mGson = new Gson();
        selList = new ArrayList<>();
        if (mBundle.containsKey(JSONKeys.Voter.ChooseList)) {
            List<Candidate> tempList = mBundle.getParcelableArrayList(JSONKeys.Voter.ChooseList);
         //   List<Candidate>  tempList = unpackVoterList(mBundle.getString(JSONKeys.Voter.ChooseList));
            LogUtils.i("mBundle.containsKey(JSONKeys.Voter.ChooseList)" + tempList.size());
            selList = new ArrayList<>(tempList);
        }
        canAdapter = new SearchCandidateAdapter(mContext, selList);
        candidateGv.setIAdapter(canAdapter);
        recordMap = new HashMap<>();
        recordList = new ArrayList<>();
        if (mBundle.containsKey(JSONKeys.Voter.AlreadyVote)) {

            List<Candidate> tempList = mBundle.getParcelableArrayList(JSONKeys.Voter.AlreadyVote);
          //  List<Candidate>    tempList = unpackVoterList(mBundle.getString(JSONKeys.Voter.AlreadyVote));

            LogUtils.i("mBundle.containsKey(JSONKeys.Voter.AlreadyVote)" + tempList.size());
//            recordList.addAll(tempList);
            recordList = new ArrayList<>(tempList);
            LogUtils.i("recordList.size " + recordList.size());
            for (int i = 0; i < recordList.size(); i++) {
                LogUtils.i("recordList info  " + recordList.get(i).toString());
                recordMap.put(recordList.get(i).voterId, i);
            }
        }
        String data = mBundle.getString(JSONKeys.Voter.ElectionData);
        election = new Gson().fromJson(data, SelectedElection.class);
        posInfo = mBundle.getParcelable(JSONKeys.Voter.Positions);
        LogUtils.e("posInfo "+posInfo.toString());
        updatePosDesc(posInfo);
    }

//    private ArrayList<Candidate> unpackVoterList(String src) {
//        ArrayList<Candidate> tempList = new ArrayList<>();
//        if (!TextUtils.isEmpty(src)) {
//            try {
//                JSONObject jObject = new JSONObject(src);
//                JSONArray jArray = jObject.getJSONArray(JSONKeys.Voter.VoterList);
//                for (int i = 0; i < jArray.length(); i++) {
//
//                    tempList.add(mGson.fromJson(jArray.getJSONObject(i).toString(), Candidate.class));
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//        return tempList;
//    }

    private void initPosDescView() {
        descLL = (LinearLayout) findView(R.id.fragment_llSearchCandidate);
        descLL.setBackgroundColor(getResources().getColor(R.color.white));
        allowNumPromptTv = (TextView) findView(R.id.posDesc_tvAllowNumPrompt);
        selNumPromptTv = (TextView) findView(R.id.posDesc_tvSelNumPrompt);
        leastNumPromptTv = (TextView) findView(R.id.posDesc_tvLeastNumPrompt);        //设成透明
        allowNumPromptTv.setTextColor(getResources().getColor(R.color.pos_des_prompt));
        selNumPromptTv.setTextColor(getResources().getColor(R.color.pos_des_prompt));
        leastNumPromptTv.setTextColor(getResources().getColor(R.color.pos_des_prompt));

        allowNumTv = (TextView) findView(R.id.posDesc_tvAllowNum);
        selNumTv = (TextView) findView(R.id.posDesc_tvSelNum);
        leastNumTv = (TextView) findView(R.id.posDesc_tvLeastNum);


    }

    /**
     * 显示当前职位的描述（可选，已选，至少的人数）
     *
     * @param info
     */
    private void updatePosDesc(final Positions info) {

        allowNumTv.setText(info.choseableCount + "人");
        selNumTv.setText(info.selectedcount + "人");
        leastNumTv.setText(info.requireCount + "人");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.election_btnDone:
                packSearchResult();

                break;
            case R.id.election_btnQuery:
                if (TextUtils.isEmpty(searchEt.getText())) {
                    Toast.makeText(mContext, "请输入过滤条件", Toast.LENGTH_SHORT).show();
                } else {
                    onSearch(searchEt.getText().toString());
                }
                break;
            default:
                break;
        }
    }

    private void packSearchResult() {
        if (posInfo.selectedcount > posInfo.choseableCount) {
            showPromptDialog(posInfo.positionName + "最多可选" + posInfo.choseableCount + "人,当前已选" + posInfo.selectedcount + "人");
            return;
        } else if (posInfo.requireCount != 0 && posInfo.selectedcount < posInfo.requireCount) {
            showPromptDialog(posInfo.positionName + "至少选" + posInfo.requireCount + "人,当前已选" + posInfo.selectedcount + "人");
            return;
        }
        ArrayList<Candidate> chooseList = new ArrayList<>();
        for (int i = 0; i < selList.size(); i++) {
            if (posInfo.positionName.equals(selList.get(i).getPositionName())) {
                chooseList.add(selList.get(i));
            }
        }
        mBundle.putParcelableArrayList(JSONKeys.Voter.ChooseList, chooseList);
    //    app.setInfoList(chooseList);
        ((ElectionActivity) mContext).updateElectionBundle(mBundle);
        removeFragment();

    }

    @Override
    public void onLoadMore(View view) {
        if (loadMoreFooterView.canLoadMore() && canAdapter.getItemCount() > 0) {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);
            if (hasMore && !TextUtils.isEmpty(searchEt.getText()))
                new SearchTask().execute(searchEt.getText().toString());
            else {
                Toast.makeText(mContext, "当前没有更多加载项", Toast.LENGTH_SHORT).show();
                loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
            }
        } else {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
        }
    }

    private void onSearch(String str) {
        if (!TextUtils.isEmpty(str)) {
            currentCount = 0; //重置可读取的数据量
            totalCount = 0;
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
            new SearchTask().execute(str);
        }
    }

//    class SearchWatcher implements TextWatcher {
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            LogUtils.i("beforeTextChanged " + s);
//
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            LogUtils.i("onTextChanged " + s);
//            if (!TextUtils.isEmpty(s)) {
//                onSearch(s.toString());
//
//            }
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
//
//        }
//    }

    class SearchTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            searchEt.setEnabled(false);
            queryBtn.setEnabled(false);
            if (totalCount == 0) {
                showProgressDialog("正在检索请稍后....");
            }
        }

        @Override
        protected String doInBackground(String... params) {
            return mExampleClient.searchVoter(election.regionId, params[0], QUERY_COUNT, currentCount);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            LogUtils.i("搜索结果" + s);
            //  loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
            searchEt.setEnabled(true);
            queryBtn.setEnabled(true);
            if (totalCount == 0)
                dismissDialog();
            if (TextUtils.isEmpty(s)) {
            } else {
                try {
                    JSONObject retJson = new JSONObject(s);
                    int retCode = CommonUtil.GetJsonIntValue(retJson, JSONKeys.Voter.ResultCode, -1);
                    if (retCode != 0) {
                        Toast.makeText(mContext, mExampleClient.getErrorMessage(retCode), Toast.LENGTH_SHORT).show();
                    } else {
                        parseSearchResult(retJson);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void parseSearchResult(JSONObject retJson) throws JSONException {
        JSONArray jsonArray = retJson.getJSONArray(JSONKeys.Voter.VoterList);

        totalCount = CommonUtil.GetJsonIntValue(retJson, JSONKeys.Voter.TotalCount, 0);
        if (totalCount < QUERY_COUNT) {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
        }
        currentCount += jsonArray.length();
        hasMore = totalCount > currentCount;
        LogUtils.e("totalCount = "+totalCount+" , currentCount = "+currentCount);
        ArrayList<Candidate> filterList = new ArrayList<>();
        ArrayList<Integer> idList = new ArrayList<>();
        for (int i = 0; i < selList.size(); i++) {

            if (posInfo.positionId == selList.get(i).getPositionId()) {
                LogUtils.e(" selList.get(i).getPositionId() "+ selList.get(i).getPositionId());
                filterList.add(selList.get(i));
                idList.add(selList.get(i).voterId);
            }
        }

        selList.clear();
        selList.addAll(filterList);
        for (int i = 0; i < jsonArray.length(); i++) {
            Candidate info = mGson.fromJson(jsonArray.getJSONObject(i).toString(), Candidate.class);
            LogUtils.e(" info "+ info.toString());

            //列表中不存在的项添加
            if (!idList.contains(info.voterId)) {
                if (recordMap.containsKey(info.voterId)) {
                    //搜索到了已被标记为其他职位的候选人
                    int index = recordMap.get(info.voterId);
                    if (index != -1 && index < recordList.size()) {
                        info.setPositionId(recordList.get(index).getPositionId());
                        info.setPositionName( recordList.get(index).getPositionName());
                    }
                }
                selList.add(info);

            }
        }
        canAdapter.notifyDataSetChanged();

    }

    /**
     * 候选人信息中职位名称的处理
     *
     * @param position
     */
    private void updateCanditaInfo(final int position) {
        Candidate canInfo = selList.get(position);

        if ("2".equals(posInfo.restriction) && "男".equals(canInfo.voterGender)) {
            Toast.makeText(mContext, "性别不符合要求", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!posInfo.positionName.equals(canInfo.getPositionName())) {
            //!posInfo.positionName.equals(canInfo.positionName在职位选举开始就有候选人列表使好使，候选人选举，职位列表为空，不好使
            //当前职位名称不等于候选人信息已有职位名称时，对候选人赋值
            canInfo.setPositionId( posInfo.positionId);
            canInfo.setPositionName(posInfo.positionName);
            // canInfo.posIndex = lastPosPosition;
            posInfo.selectedcount++;
        } else {
            canInfo.setPositionId( 0);
            canInfo.setPositionName("");
            canInfo.posIndex = -1;
            posInfo.selectedcount--;
        }
        canAdapter.notifyDataSetChanged();
//        canAdapter.notifyItemChanged(position);
        updatePosDesc(posInfo);
    }

}
